<?php

class Pldkp_Form extends ZendX_JQuery_Form 
{
    /**
     * Setup the default appearance of the form.
     * 
     * @param array $options
     */
    public function __construct($options = null)
    {
        // Add our custom validators and decorators as default
        $this->addElementPrefixPath('Pldkp_Validate', 'Pldkp/Validate/', 'validate');
        $this->addElementPrefixPath('Pldkp_Form_Decorator', 'Pldkp/Form/Decorator/', 'decorator');
        
        parent::__construct($options);
        $this->setupDecorators();
    }
    
    /**
     * Function copied from the ZendX Jquery form set view.
     * This enables custom view helpers from Pldkp_View_Helper so they 
     * are always avaible.
     */
    public function setView(Zend_View_Interface $view = null)
    {
        if (null !== $view) {
            if (false === $view->getPluginLoader('helper')->getPaths('Pldkp_View_Helper')) {
                $view->addHelperPath('Pldkp/View/Helper', 'Pldkp_View_Helper');
            }
        }
        return parent::setView($view);
    }
    
    /**
     * This functions sets up the default appearance of the form.
     * Basically it removes the dt/dd wrapper and sets up submits without labels.
     * 
     * It also handles restoring the proper state to jquery elements, as the decoraters
     * needs to be reset.
     */
    protected function setupDecorators()
    {
        $this->setDecorators(array(
            'FormElements',
            array('HtmlTag', array('tag' => 'div', 'class' => 'input-form')),
            'Form',
        ));
        
        // Setup decorators for specific elements
        foreach ($this->getElements() as $element) {
            
            $element->clearDecorators();
            
            // Restore the elements view helper
            // Zend form elements are rendered with a special view helper
            if ($element instanceof ZendX_JQuery_Form_Element_UiWidget) {
                $element->addDecorator('UiWidgetElement');
            } else {
                $element->addDecorator('ViewHelper');
            }
            
            // Setup the decorators we need
            $element->addDecorators(array(
                'DivWrapper',
                'Errors',
                array('Description', array('placement' => 'prepend')),
                array('Label', array('tag' => 'div')),
            ));

            // Remove labels from submits and wrap them in a div
            if ($element instanceof Zend_Form_Element_Submit) {
                $element->removeDecorator('Label');
                $element->addDecorator('HtmlTag', array('tag' => 'div'));
            }
            
            // Remove labels from submits and wrap them in a div
            if ($element instanceof Zend_Form_Element_Hidden) {
                $element->clearDecorators();
                $element->addDecorator('ViewHelper');
                $element->addDecorator('Errors');
            }
        }
    }
}